package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"time"
)

func BackupFile(file string) error {
	now := time.Now().Format("20060102_150405")
	bakName := fmt.Sprintf("%s_%s.bak", file, now)
	written, err := CopyFile(file, bakName)
	log.Printf("backup: %s, %s,%d, %v", file, bakName, written, err)
	if written == 0 || err != nil {
		return fmt.Errorf("backup failed:%d, %v", written, err)
	}
	return nil
}

func CopyFile(srcName, dstName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return 0, err
	}
	defer src.Close()
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return 0, err
	}
	defer dst.Close()
	return io.Copy(dst, src)
}

func AddHost2TmpFile(hostFile, host, ip string) (tmpFileName string, err error) {
	tmpFile, err := ioutil.TempFile("", "hosts_")
	if err != nil {
		return "", err
	}
	defer tmpFile.Close()
	tmpFileName = tmpFile.Name()

	f, err := os.Open(hostFile)
	if err != nil {
		return
	}
	defer f.Close()

	buf := bufio.NewReader(f)
	matched := false
	for {
		line, _, eof := buf.ReadLine()
		if eof == io.EOF {
			break
		}
		if IsMatchHostLine(string(line), host) {
			//now := time.Now().Format("2006-01-02 15:04:05")
			//tmpFile.WriteString(fmt.Sprintf("# add by awesome_host @%s\r\n", now))
			tmpFile.WriteString(fmt.Sprintf("%s %s\r\n", ip, host))
			matched = true
		} else {
			tmpFile.Write(line)
			tmpFile.Write([]byte("\r\n"))
		}
	}
	if !matched {
		tmpFile.WriteString(fmt.Sprintf("%s %s\r\n", ip, host))
	}
	return tmpFileName, nil
}

func IsMatchHostLine(line, host string) bool {
	//reg := regexp.MustCompile("^[^#].* github.com")
	//if !reg.MatchString(line) {
	//	return false
	//}
	vs := strings.Fields(strings.TrimSpace(line))
	if len(vs) == 2 {
		if IsIP(vs[0]) && vs[1] == host {
			return true
		}
	}
	return false
}
